
package com.funo.government.info.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.funo.government.info.R;
import com.funo.government.info.bean.VersionInfo;
import com.funo.government.info.constant.Constant;
import com.funo.government.info.utils.BusinessException;
import com.funo.government.info.utils.BusinessResolver.BusinessCallback;
import com.funo.government.info.utils.DownFile;
import com.funo.government.info.utils.GovernmentResolver;
import com.funo.government.info.utils.RequestTask;
import com.funo.government.info.utils.Utils;

public class MoreFragment extends Fragment implements OnClickListener {

    private SharedPreferences preferences;

    private CheckBox cbSwitchPushSettings;

    private RequestTask updateCheckTask;

    private AlertDialog updateDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_more, null);
        view.findViewById(R.id.layoutDownloadManage).setOnClickListener(this);
        view.findViewById(R.id.layoutAreaSettings).setOnClickListener(this);
        view.findViewById(R.id.layoutPushSettings).setOnClickListener(this);
        view.findViewById(R.id.layoutAbout).setOnClickListener(this);
        view.findViewById(R.id.layoutNoticeRemind).setOnClickListener(this);
        view.findViewById(R.id.layoutUpdateCheck).setOnClickListener(this);
        TextView tvCurrentArea = (TextView) view.findViewById(R.id.tvCurrentArea);
        String areaName = preferences.getString(Constant.PRE_KEY_AREA_NAME,
                getString(R.string.default_area_name));
        tvCurrentArea.setText(areaName);
        cbSwitchPushSettings = (CheckBox) view.findViewById(R.id.cbSwitchPushSettings);
        cbSwitchPushSettings.setChecked(preferences
                .getBoolean(Constant.PRE_KEY_PUSH_SETTINGS, true));
        cbSwitchPushSettings.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                preferences.edit().putBoolean(Constant.PRE_KEY_PUSH_SETTINGS, isChecked).commit();
                
                Utils.ProcessPullService(getActivity());
            }
        });
        return view;
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.layoutDownloadManage:
                intent = new Intent(getActivity(), FileManagerActivity.class);
                startActivity(intent);
                break;
            case R.id.layoutPushSettings:
                cbSwitchPushSettings.setChecked(!cbSwitchPushSettings.isChecked());
                break;
            case R.id.layoutAbout:
                intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.layoutAreaSettings:
                intent = new Intent(getActivity(), AreaSelectActivity.class);
                startActivityForResult(intent, AreaSelectActivity.REQUEST_CODE);
                break;

            case R.id.layoutNoticeRemind:
                intent = new Intent(getActivity(), NoticeListActivity.class);
                startActivity(intent);
                break;

            case R.id.layoutUpdateCheck:
                updateCheck();

                break;

        }
    }

    private void updateCheck() {
        updateCheckTask = GovernmentResolver.getVersion(new BusinessCallback<VersionInfo>() {

            @Override
            public void onSuccess(VersionInfo versionInfo) {
                if (versionInfo == null) {
                    Toast.makeText(getActivity(), R.string.not_new_version, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
                PackageManager pm = getActivity().getPackageManager();
                try {
                    PackageInfo pi = pm.getPackageInfo(getActivity().getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
                    if (versionInfo.versionId > pi.versionCode) {
                        showUpdateDialog(versionInfo);
                    } else {
                        Toast.makeText(getActivity(), R.string.not_new_version, Toast.LENGTH_SHORT)
                                .show();

                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onError(BusinessException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), R.string.not_new_version, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showUpdateDialog(final VersionInfo versionInfo) {
        if (updateDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setCancelable(false);
            builder.setTitle(R.string.find_new_version);
            builder.setMessage(versionInfo.updateLog);
            builder.setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent in = new Intent(getActivity(), DownFile.class);
                    in.putExtra("url", versionInfo.versionIP);
                    getActivity().startService(in);
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(R.string.later, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            updateDialog = builder.create();
        }
        if (!updateDialog.isShowing()) {
            updateDialog.show();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (updateCheckTask != null) {
            updateCheckTask.cancel(true);
            updateCheckTask = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AreaSelectActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            String areaId = data.getStringExtra(Constant.PRE_KEY_AREA_ID);
            String areaName = data.getStringExtra(Constant.PRE_KEY_AREA_NAME);

            MainActivity main = (MainActivity) getActivity();
            main.loadNav(areaId);
            // if (!areaId.equals("1")) {
            // ArrayList<NavItem> navs = new ArrayList<NavItem>();
            // NavItem n1 = new NavItem("军事", "1",
            // "http://www.qq.com/mobile/news.htm?mil");
            // NavItem n2 = new NavItem("财经", "2",
            // "http://www.qq.com/mobile/news.htm?finance");
            // NavItem n3 = new NavItem("体育", "3",
            // "http://www.qq.com/mobile/news.htm?sports");
            // navs.add(n1);
            // navs.add(n2);
            // navs.add(n3);
            // main.buildTab(navs);
            // } else {
            // ArrayList<NavItem> navs = new ArrayList<NavItem>();
            // NavItem n1 = new NavItem("首页", "1", "http://www.qq.com/mobile/");
            // NavItem n2 = new NavItem("新闻", "2",
            // "http://www.qq.com/mobile/news.htm?ent");
            // NavItem n3 = new NavItem("通告", "3",
            // "http://www.qq.com/mobile/appandroid.htm");
            // navs.add(n1);
            // navs.add(n2);
            // navs.add(n3);
            //
            // main.buildTab(navs);
            // }
        }
    }

}
